<template>
  <view class="profile-edit-page">
    <view class="page-content">
      <!-- 基本信息 -->
      <view class="form-card content-card">
        <text class="section-title">基本信息</text>
        
        <u-form :model="formData" ref="formRef" :rules="formRules" :error-type="['toast']">
          <!-- 昵称 -->
          <u-form-item label="昵称" prop="nickname" class="form-item">
            <u-input 
              v-model="formData.nickname"
              placeholder="请输入昵称"
              :border="false"
              clearable
            />
          </u-form-item>
          
          <!-- 邮箱 -->
          <u-form-item label="邮箱" prop="email" class="form-item">
            <u-input 
              v-model="formData.email"
              placeholder="请输入邮箱"
              :border="false"
              clearable
            />
          </u-form-item>
        </u-form>
      </view>

      <!-- 保存按钮 -->
      <view class="save-section">
        <u-button 
          type="primary" 
          @click="saveProfile"
          :loading="saving"
          class="save-btn"
        >
          保存修改
        </u-button>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/api/index.js'

export default {
  data() {
    return {
      formData: {
        nickname: '',
        email: ''
      },
      formRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ]
      },
      saving: false
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  methods: {
    // 检查登录状态（仅检查，不弹窗）
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('user_info')
      
      console.log('🔍 登录状态检查:', {
        hasToken: !!token,
        tokenLength: token ? token.length : 0,
        hasUserInfo: !!userInfo,
        userInfo: userInfo ? { id: userInfo.id, nickname: userInfo.nickname } : null
      })
      
      if (!token) {
        console.warn('❌ Token不存在，需要登录')
        return false
      }
      
      console.log('✅ 用户已登录，token存在')
      return true
    },
    
    // 显示登录提示并跳转
    showLoginPrompt(message = '请先登录后再编辑资料') {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false,
        success: () => {
          uni.reLaunch({
            url: '/pages/login/index'
          })
        }
      })
    },
    
    async initPage() {
      if (!this.checkLoginStatus()) {
        this.showLoginPrompt()
        return
      }
      await this.loadUserInfo()
    },
    
    async loadUserInfo() {
      try {
        const response = await apiService.user.getUserProfile()
        console.log('✅ 用户信息加载成功:', response)
        
        // API返回格式：{code: 200, message: "获取用户信息成功", data: {...}}
        const userInfo = response.data || response
        
        this.formData = {
          nickname: userInfo.nickname || '',
          email: userInfo.email || ''
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        
        // 如果是认证错误，清除token并跳转登录
        if (error.message && (error.message.includes('401') || error.message.includes('Unauthorized'))) {
          console.warn('Token已过期，清除登录状态')
          uni.removeStorageSync('token')
          uni.removeStorageSync('refresh_token')
          uni.removeStorageSync('user_info')
          
          uni.showModal({
            title: '登录已过期',
            content: '请重新登录',
            showCancel: false,
            success: () => {
              uni.reLaunch({
                url: '/pages/login/index'
              })
            }
          })
          return
        }
        
        // 如果是404错误，可能是新用户，使用默认值
        if (error.message && error.message.includes('404')) {
          console.log('用户资料不存在，使用本地缓存或默认值')
          const cachedUserInfo = uni.getStorageSync('user_info')
          if (cachedUserInfo) {
            this.formData = {
              nickname: cachedUserInfo.nickname || '新用户',
              email: cachedUserInfo.email || ''
            }
          } else {
            // 如果连本地缓存都没有，使用默认值
            this.formData = {
              nickname: '新用户',
              email: ''
            }
          }
          return
        }
        
        uni.showToast({
          title: error.message || '加载用户信息失败',
          icon: 'none'
        })
      }
    },
    
    async saveProfile() {
      try {
        // 检查登录状态
        if (!this.checkLoginStatus()) {
          this.showLoginPrompt('登录已过期，请重新登录')
          return
        }
        
        // 表单验证
        await this.$refs.formRef.validate()
        
        this.saving = true
        
        // 调用API更新用户资料
        const response = await apiService.user.updateProfile({
          nickname: this.formData.nickname,
          email: this.formData.email
        })
        
        console.log('✅ 用户资料更新成功:', response)
        
        // 更新本地缓存的用户信息
        const cachedUserInfo = uni.getStorageSync('user_info') || {}
        const updatedUserInfo = {
          ...cachedUserInfo,
          nickname: this.formData.nickname,
          email: this.formData.email
        }
        uni.setStorageSync('user_info', updatedUserInfo)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存用户资料失败:', error)
        
        let errorMessage = '保存失败'
        
        // 根据不同错误类型提供更友好的提示
        if (error.message) {
          if (error.message.includes('401') || error.message.includes('Unauthorized')) {
            errorMessage = '登录已过期，请重新登录'
            // 清除登录状态
            uni.removeStorageSync('token')
            uni.removeStorageSync('refresh_token')
            uni.removeStorageSync('user_info')
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/index'
              })
            }, 2000)
          } else if (error.message.includes('404')) {
            errorMessage = '用户不存在，请重新登录'
          } else if (error.message.includes('400')) {
            errorMessage = '提交的信息格式不正确'
          } else if (error.message.includes('网络')) {
            errorMessage = '网络连接失败，请检查网络'
          } else {
            errorMessage = error.message
          }
        }
        
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        })
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-edit-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.page-content {
  padding: 32rpx;
}

.content-card {
  background: white;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 32rpx;
  display: block;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.save-section {
  padding: 0 32rpx;
}

.save-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
}
</style>